package cn.com.algery.temp.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.algery.temp.domain.User;
import cn.com.algery.temp.service.UserService;


public class CustomRealm extends AuthorizingRealm{
    private static final Logger logger = LoggerFactory.getLogger(CustomRealm.class);
    @Autowired
    private UserService userService;
    /**
     * User authorization authentication
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("======User authorization authentication======");
        String userName = principalCollection.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(userService.queryRolesByName(userName));
        return simpleAuthorizationInfo;
    }
    /**
     * User login authentication
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("======User login authentication======");
        // The subject's login() will call this method.
        // The password matching will be done in the Frei Authorticating Realm.
        String userName = authenticationToken.getPrincipal().toString();
        User user = userService.queryUserByName(userName);
        if (user!=null) {
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUser_account(), user.getUser_pwd(), "peng");
            return authenticationInfo;
        } else {
        	throw new UnknownAccountException("User does not exist！");
        }
        
    }

}